package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.converter.LocalDateTimeConverter;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService iEmployeeService;

    @GetMapping("/export")
    public R downloadExport(HttpServletResponse response) throws IOException {

    /*    try {
            //PrintWriter writer = response.getWriter();
            ServletOutputStream outputStream = response.getOutputStream();
            //response.setContentType("image/jpeg");
            FileInputStream fileInputStream = new FileInputStream(new File(filePath,name));
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        response.setHeader("Content-Disposition","attachment;filename=employee.xlsx");
        List<Employee> list = iEmployeeService.list();
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream,Employee.class).registerConverter(new LocalDateTimeConverter()).sheet("员工数据").doWrite(list);

        outputStream.close();

        return R.success(null);
    }

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){


        if (employee == null || StringUtils.isEmpty(employee.getUsername() ) || StringUtils.isEmpty(employee.getPassword())){

            return R.error("用户名密码不能为空");
        }
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();

        qw.eq(Employee::getUsername,employee.getUsername());
        Employee existEmp = iEmployeeService.getOne(qw);

        if (existEmp == null){

            return R.error("账号不存在");
        }

        if (existEmp.getStatus() == 0){

            return R.error("账号已经禁用");

        }

        String password = existEmp.getPassword();//密文
        String password1 = employee.getPassword();//明文

        password1 = DigestUtils.md5DigestAsHex(password1.getBytes());

        if (password.equals(password1)){
            //比对成功，返回code：1和data：用户信息
            //将用户数据存入会话中session，如何获取session
            existEmp.setPassword(null);
            session.setAttribute("shuju",existEmp.getId());
            return R.success(existEmp);


        }

        return R.error("查询错误");

    }

    @PostMapping("/logout")
    public R logout(HttpSession session){

        session.removeAttribute("shuju");

        return R.success("退出成功");

    }

    @PostMapping
    public R addEmployee(@RequestBody Employee employee,HttpSession session){


        //Long shuju = (Long) session.getAttribute("shuju");

        String pasword = DigestUtils.md5DigestAsHex("123456".getBytes());

        employee.setPassword(pasword);
  /*      employee.setCreateTime(LocalDateTime.now());

        employee.setCreateUser(shuju);

        employee.setUpdateTime(LocalDateTime.now());

        employee.setUpdateUser(shuju);
*/
        boolean save = iEmployeeService.save(employee);
        if (save) {
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }
    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize,String name){

        IPage<Employee> p = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)){
        qw.like(Employee::getUsername,name);
        }
        IPage<Employee> page1 = iEmployeeService.page(p, qw);
        long total = page1.getTotal();
        List<Employee> records = page1.getRecords();
        Map data = new HashMap();
        data.put("records", records);
        data.put("total",total);
        return R.success(data);
    }

    @PutMapping
    public R updateStatus(@RequestBody Employee employee,HttpSession session){
    /*   employee.setUpdateTime(LocalDateTime.now());
       Long id = (Long) session.getAttribute("shuju");

        employee.setUpdateUser(id);
        employee.setUpdateTime(LocalDateTime.now());

*/

        boolean b = iEmployeeService.updateById(employee);
        return R.success("修改成功");
    }
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id){

        Employee employee = iEmployeeService.getById(id);

        return R.success(employee);
    }


}
